package com.logistic.server.common.config;

import com.logistic.server.common.handler.AuthorizationInterceptor;
import com.logistic.server.common.resolver.ArgumentResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.List;

/**
 * MVC配置
 * @author swen
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private ArgumentResolver argumentResolver;

    @Resource
    private AuthorizationInterceptor authorizationInterceptor;

    @Value("${spring.web.resources.static-locations}")
    private String path;

    /**
     * 静态资源映射
     * @param registry r
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/upload/**").addResourceLocations("file:" + path);
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
    }

    /**
     * 注入登录用户入参
     * @param argumentResolvers 入参
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(argumentResolver);
    }

    /**
     * 通过判断是否有 @LoginRequired 注解 决定是否需要登录
     * @param registry 拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 拦截所有请求
        registry.addInterceptor(authorizationInterceptor).addPathPatterns("/**");
    }

}
